package gui;

import gui.AddCoordinateDialog.AddCoordinateFrame;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import logic.objects.Problem;

public class SetupFrame extends JFrame implements ActionListener {
	JButton delete;
	JButton apply;
	JButton add;
	JButton cancel;
	SetupPanel panel;
	Boolean geaendert = false;
	AcoFrame frame;

	public SetupFrame(Problem problem, AcoFrame frame) {
		this.frame = frame;
		this.setTitle("Lösen des TSP mit Hilfe verschiedener ACO Algorithmen");
		this.setSize(GraphicVariables.MAX_WIDTH_SetupFrame,
				GraphicVariables.MAX_HEIGHT_SetupFrame);
		this.setLocation(50, 50);
		this.setLayout(new GridLayout(1, 2));
		panel = new SetupPanel(problem);
		JPanel buttonPanel = new JPanel(new GridLayout(4, 1));
		add(panel);
		delete = new JButton("Löschen");
		apply = new JButton("Übernehmen");
		add = new JButton("Hinzufügen");
		cancel = new JButton("Abbrechen");
		add(buttonPanel);
		buttonPanel.add(add);
		add.addActionListener(this);
		buttonPanel.add(delete);
		delete.addActionListener(this);
		buttonPanel.add(cancel);
		cancel.addActionListener(this);
		buttonPanel.add(apply);
		apply.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == delete) {
			panel.removeSelected();
			geaendert = true;
		}
		if (e.getSource() == apply) {
			if (!geaendert || applyQuestion()) {
				panel.applyChanges();
				frame.reset();
				this.setVisible(false);
			}
		}
		if (e.getSource() == cancel) {
			if (!geaendert || cancleQuestion())
				this.setVisible(false);
		}
		if (e.getSource() == add) {
			new AddCoordinateFrame(panel).setVisible(true);
			geaendert = true;
		}
	}

	public boolean cancleQuestion() {
		int n = JOptionPane.showConfirmDialog(this,
				"Alle Änderungen gehen verloren. Soll fortgefahren werden?",
				"Fenster schließen", JOptionPane.YES_NO_OPTION);
		if (n == 0) {
			return true;

		} else
			return false;
	}

	public boolean applyQuestion() {
		int n = JOptionPane
				.showConfirmDialog(
						this,
						"Alle gespeicherten Ergebnisse gehen verloren. Soll fortgefahren werden?",
						"Änderungen übernehmen", JOptionPane.YES_NO_OPTION);
		if (n == 0) {
			return true;

		} else
			return false;
	}
}
